<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card>
      <el-row :gutter="25">
        <el-col :span="10">
          <!-- 搜索添加 clearable就是点击删除小标记时候触发的-->
          <el-input placeholder="请输入搜索内容" v-model="queryInfo.queryName" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="10">
          <el-input placeholder="请输入搜索角色" v-model="queryInfo.queryRole" clearable @clear="getUserListRole">
            <el-button slot="append" icon="el-icon-search" @click="getUserListRole"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="密码" prop="password"></el-table-column>
        <el-table-column label="角色" prop="role"></el-table-column>
        <el-table-column label="状态" prop="state">
          <!-- scope.row 就是当前行的信息 作用域插槽-->
          <!--scope 是elementUI自带的，可以封装:data="userList"中所有的数据状态          -->
          <template slot-scope="scope">
            <!--      状态码【true or false】： {{scope.row.state}}-->
<!--            {{scope.row}}-->
            <el-switch v-model="scope.row.state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button type="primary" icon="el-icon-edit" size="mini"@click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除 -->
            <el-tooltip effect="dark" content="删除" placement="top-start" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 权限el-tooltip:用于提示信息  content="分配权限"  placement="top-start":提示信息的位置，默认在下面-->
            <el-tooltip effect="dark" content="分配权限" placement="top-start" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页
       @size-change : 每页最大变化
       @current-change : 当前最大变化
       layout : 功能组件
       -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[1, 2, 5, 100]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>

    </el-card>

    <!--新增用户区域-->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%"
               @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules"
               ref="addFormRef" label-width="70px">
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <!-- 角色 -->
        <el-form-item label="角色" prop="role">
          <el-select v-model="addForm.role" placeholder="请选择角色">
            <el-option label="超级管理员" value="超级管理员"></el-option>
            <el-option label="普通管理员" value="普通管理员"></el-option>
            <el-option label="普通用户" value="普通用户"></el-option>
          </el-select>
        </el-form-item>
        <!-- 状态 -->
        <el-form-item label="状态" prop="state">
          <el-switch v-model="addForm.state"></el-switch>
        </el-form-item>
      </el-form>
      <!-- 内容底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%" @colse="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "User",
  created() {
    //初始调用
    this.getUserList();
  },
  data() {
    return {
      //查询信息实体
      queryInfo: {
        queryName: "", //查询页
        queryRole:"", //角色名
        pageNum: 1, //当前页
        pageSize: 5 //每页最大数
      },
      userList: [], //用户列表
      total: 0, //总记录数目
      addDialogVisible: false, //对话框状态
      addForm: {
        username: "",
        password: "",
        email: "",
        role:"",
        state:false
      },
      //修改用户信息
      editForm: {},
      //显示/隐藏修改用户栏
      editDialogVisible: false,
      //添加表单验证
      addFormRules: {
        username: [
          {required: true, message: "请输入用户名", trigger: "blur"},
          {min: 5, max: 8, message: "长度在 5 到 8 个字符", trigger: "blur"}
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
          {min: 6, max: 8, message: "长度在 6 到 8 个字符", trigger: "blur"}
        ],
        email: [
          {required: true, message: "请输入邮箱", trigger: "blur"},
          {min: 5, max: 15, message: "请输入正确邮箱地址", trigger: "blur"}
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
      },
      //修改表单验证
      editFormRules: {
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
          {min: 6, max: 8, message: "长度在 6 到 8 个字符", trigger: "blur"}
        ],
        email: [
          {required: true, message: "请输入邮箱", trigger: "blur"},
          {min: 5, max: 15, message: "请输入正确邮箱地址", trigger: "blur"}
        ],
      },

    }
  },
  methods: {
    //获取所有用户信息
    async getUserList() {
      console.log("测试getUserList！！作用：刷新表单")
      //传递参数，地址，config后为实际传参 queryInfo接收后端的res_string
      const {data: res} = await this.$http.get("/alluser", {params: this.queryInfo});
      console.log("getUserList"+res.data);
      this.userList = res.data;
      this.total = res.number;
    },
    //根据角色名获取所有用户信息
    async getUserListRole() {
      console.log("测试getUserListRole！！作用：刷新表单")
      const {data: res} = await this.$http.get("/alluserRole", {params: this.queryInfo});
      console.log("getUserListRole:"+res.data);
      this.userList = res.data;
      this.total = res.number;
    },

    //最大数
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getUserList();
    },

    //pageNum的触发
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getUserList();
    },

    //记录改变的状态
    //TODO 不加async会出错  在if中补这个可以解决this.$http.put(`/userState?id=${userInfo.id}&state=${userInfo.state}`);
    async userStateChanged(userInfo) {
      const {data: res} = await this.$http.put(`/userState?id=${userInfo.id}&state=${userInfo.state}`);
      console.log("res:" + res)
      if (res != "success") {
        userInfo.state = !userInfo.state; //保持不变 因为错了，前面修改有误
        return this.$message.error("操作失败！");
      }
      this.$message.success("操作成功！");
    },
    //监听添加用户 resetFields重置表单
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        console.log(valid);
        if (!valid) return;
        // 发起请求
        const {data: res} = await this.$http.post("addUser", this.addForm);
        if (res != "success") {
          return this.$message.error("操作失败！！！");
        }
        this.$message.success("操作成功！！！");
        //隐藏 刷新表单
        this.addDialogVisible = false;
        await this.getUserList();
      })
    },

    //删除用户
    async deleteUser(id) {
      // 弹框
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).catch(err => err)

      // 根据confirmResult来判断结果
      if (confirmResult != 'confirm') {
        return this.$message.info("已取消删除");
      }
      const {data: res} = await this.$http.delete("deleteUser?id=" + id);
      if (res != "success") {
        return this.$message.error("操作失败！！！");
      }
      this.$message.success("操作成功！！！");
      await this.getUserList();

    },
    //显示对话框
    async showEditDialog(id) {
      const {data: res} = await this.$http.get("getUpdate?id=" + id);
      this.editForm = res; //查出数据反填表单
      this.editDialogVisible = true; //显示
    },
    //关闭窗口
    editDialogClosed() {
      this.$refs.editFormRef.resetFields(); //重置信息
    },
    //确认修改
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        //发起修改请求
        const {data: res} = await this.$http.put("editUser", this.editForm);
        if (res != "success") return this.$message.error("操作失败!");
        this.$message.success("操作成功");
        //隐藏
        this.editDialogVisible = false;
        await this.getUserList();
      })
    }

  },

}
</script>

<style lang="less" scoped>

</style>